<?php
/**
 * Created by PhpStorm.
 * User: minicart
 * Date: 2018/10/16
 * Time: 11:12
 */
namespace app\models;

use think\Model;

/**
 * 订单管理表
 * Class ContractModel
 * @package app\models
 */
class ContractModel extends Model
{
    protected $table = 'edu_contract';

    /**
     * 订单管理列表
     * @param $param
     *
     * @throws \think\exception\DbException
     *
     * @return array
     */
    public function getContractLists($param)
    {
        $page = isset($param['page']) ? (int) $param['page'] : 1;
        $listRows = isset($param['limit']) ? (int) $param['limit'] : 10;
        $where = [];
        $where['student_id'] = array('gt',0);  //学生ID不为NULL

        //学员姓名
        if (isset($param['student_name']) && '' !== $param['student_name']) {
            $where['student_name'] = ['like', '%'.$param['student_name'].'%'];
        }
        //学员年级
        if (isset($param['grade']) && '' !== $param['grade']) {
            $where['grade'] = $param['grade'];
        }


        //订单编号
        if (isset($param['contract_number']) && '' !== $param['contract_number']) {
            $where['contract_number'] = ['like', '%'.$param['contract_number'].'%'];
        }


        //签约时间

        if (isset($param['start_date']) && '' !== $param['start_date'] && isset($param['end_date']) && '' !== $param['end_date']) {
            $where['signing_date'] = array('between', array($param['start_date'],$param['end_date']));
        }


        //校区
        if (isset($param['campus_id']) && '' !== $param['campus_id']) {
            $where['campus_id'] = $param['campus_id'];
        }else{
			if(get_current_type() == 4 || get_current_type() == 5){/*校区员工数据权限*/
				$where['campus_id'] = get_current_campus_id();
			}elseif (get_current_type() == 3 || get_current_type() == 2){/*系统区域数据权限*/
				$where['campus_id'] = ['in',get_current_campus_id()];
			}
		}

        //订单状态
        if (isset($param['type']) && '' !== $param['type']) {
            if($param['type'] == 'all'){
                $where['status'] = ['in','1,2,3'];  //全部
            }else if($param['type'] == 'stay'){
              //  $where['status'] = ['in','2,3'];
                $where['status'] = ['in','2']; //未收款
            }else if($param['type'] == 'part'){  //部分收款
                $where['status'] = ['in','3'];
            }
        }

        $listData = self::where($where)
            ->order('create_time desc')
            ->paginate($listRows, false, ['page' => $page])
            ->toArray();

        $total_amount = 0;
        $preferential = 0;
        $amount = 0;
        $amount_course_total = 0;
        $amount_grades_total = 0;
        $amount_goods_total = 0;
        $amount_course_balance_total = 0;
        $amount_goods_balances_total = 0;
        $amount_grades_balance_total = 0;

        $stay_amount = 0;
        $stay_distributed = 0;
        $balance = 0;
        $storedvalue = 0;
        $expenditure = 0;
        $net_receipts = 0;
        $total_contract = 0;
        $StudentSubjectInfosClassModel =   new StudentSubjectInfosClassModel();
        if (!empty($listData)) {
            foreach ($listData['data'] as &$item) {
                $item['status_text'] = (1 === $item['status']) ? '启用' : '禁用';
                $item['campus_name'] = CampusModel::getById($item['campus_id'], 'campus_name');
                $item['contractor'] = UserModel::get(['id' => $item['contractor']])['name'];
                /*
                $item['contract_type'] = DictionaryModel::get(['id' =>  $item['contract_type'] ])['name'];
                */

                if($item['input_type'] == 0){
                    $item['input_type_text'] = '新生';
                }else if($item['input_type'] == 1){
                    $item['input_type_text'] = '老生';
                }
                /*
                $item['contract_type'] = DictionaryModel::get(['id' =>  $item['contract_type'] ])['name'];
                */

                $item['signing_type_text'] = DictionaryModel::get(['id' =>  $item['signing_type'] ])['name'];
                if($item['grade'] ==0 || $item['grade'] == null){
                    $item['grade'] = '-';
                }else{
                    $item['grade'] = DictionaryModel::get(['id' =>  $item['grade'] ])['name'];
                }
                $item['payee_text'] = UserModel::get(['id' => $item['payee']])['name'];
                $item['total_amount'] = sprintf("%.2f",($item['total_amount'] / 100));
                $total_amount = $total_amount +  $item['total_amount'] ;
                $item['preferential'] = sprintf("%.2f",($item['preferential'] / 100));
                $preferential = $preferential +    $item['preferential'];
                $item['amount'] =  sprintf("%.2f",($item['amount'] / 100));
                $amount = $amount +  $item['amount'];

                $amount_course = CourseContractModel::where(['contract_id' => $item['id']])->sum('payment');
                $item['amount_course'] = sprintf("%.2f",($amount_course / 100));;
                $amount_course_total = $amount_course_total + $item['amount_course'];
                $amount_grades = GradesContractModel::where(['contract_id' => $item['id']])->sum('payment');
                $item['amount_grades'] = sprintf("%.2f",($amount_grades / 100));
                $amount_grades_total = $amount_grades_total + $item['amount_grades'];
                $amount_goods = GoodsContractModel::where(['contract_id' => $item['id']])->sum('payment');
                $item['amount_goods'] = sprintf("%.2f",($amount_goods / 100));
                $amount_goods_total = $amount_goods_total +  $item['amount_goods'];


                $amount_course_balance = CourseContractModel::where(['contract_id' => $item['id']])->sum('payment_balance');
                $item['amount_course_balance'] = sprintf("%.2f",($amount_course_balance / 100));;
                $amount_course_balance_total = $amount_course_balance_total + $item['amount_course_balance'];
                $amount_grades_balance = GradesContractModel::where(['contract_id' => $item['id']])->sum('payment_balance');
                $item['amount_grades_balance'] = sprintf("%.2f",($amount_grades_balance / 100));
                $amount_grades_balance_total = $amount_grades_balance_total + $item['amount_grades_balance'];
                $amount_goods_balance = GoodsContractModel::where(['contract_id' => $item['id']])->sum('payment_balance');
                $item['amount_goods_balance'] = sprintf("%.2f",($amount_goods_balance / 100));
                $amount_goods_balances_total = $amount_goods_balances_total +  $item['amount_goods_balance'];

                $item['stay_amount'] =  sprintf("%.2f",($item['stay_amount'] / 100));
                $stay_amount = $stay_amount +  $item['stay_amount'];
                $item['stay_distributed']  = sprintf("%.2f",($item['stay_distributed'] / 100));
                $stay_distributed = $stay_distributed +   $item['stay_distributed'];

                $item['balance'] = sprintf("%.2f",($item['balance'] / 100));
                $balance = $balance +  $item['balance'] ;

                $item['storedvalue']  = sprintf("%.2f",($item['storedvalue'] / 100));
                $storedvalue = $storedvalue + $item['storedvalue'];

                $item['expenditure']  = sprintf("%.2f",($item['expenditure'] / 100));
                $expenditure = $expenditure + $item['expenditure'];

                $item['net_receipts']  = sprintf("%.2f",($item['net_receipts'] / 100));
                $net_receipts = $net_receipts + $item['net_receipts'] ;

                $item['total_contract'] = $item['total_amount'] + $item['preferential']; //优惠前总金额
                $total_contract = $total_contract + $item['total_contract'];

                //判断该合同是否已经开班【该订单是否已经开课】
                $res_infos = $StudentSubjectInfosClassModel->get(['student_id' => $item['student_id'],'contract_number'=> $item['contract_number']]); //是否已经开班
                if($res_infos){
                    $item['status_infos'] = 1;  //已经开班
                }else{
                    $item['status_infos'] = 0;  //未开班
                }

                if($item['signing_type'] == 114){
                    $item['total_contract'] = '-';
                    $item['total_amount'] = '-';
                    $item['net_receipts'] = '-';
                    $item['amount'] = '-';
                    $item['amount_course'] = '-';
                    $item['amount_grades'] = '-';
                    $item['amount_goods'] = '-';
                    $item['amount_course_balance'] = '-';
                    $item['amount_grades_balance'] = '-';
                    $item['amount_goods_balance'] = '-';
                    $item['stay_amount'] = '-';
                    $item['expenditure'] = '-';
                    $item['balance'] = '-';
                    $item['stay_distributed'] = '-';
                    $item['preferential'] = '-';
                }
            }
        }

        $item_end = [];
        $item_end['contract_number']  = '合计';
        $item_end['student_name']  = '-';
        $item_end['grade'] = '-';
        $item_end['signing_date'] = '-';
        $item_end['campus_name'] = '-';
        $item_end['contractor'] = '-';
        $item_end['contract_type'] = '-';
        $item_end['signing_type'] = -1;
        $item_end['payee_text'] = '-';
        $item_end['signing_type_text'] = '-';
        $item_end['input_type_text'] = '-';



        $item_end['storedvalue'] =  sprintf("%.2f",$storedvalue);   //储值
        $item_end['expenditure'] =  sprintf("%.2f",$expenditure);   //支出
        $item_end['net_receipts'] =  sprintf("%.2f",$net_receipts);   //实收
        $item_end['total_amount'] = sprintf("%.2f",$total_amount);   //总额
        $item_end['preferential'] = sprintf("%.2f",$preferential);   //优惠
        $item_end['amount'] = sprintf("%.2f",$amount);    //项目收费
        $item_end['amount_course'] = sprintf("%.2f",$amount_course_total);    //课程收费
        $item_end['amount_grades'] = sprintf("%.2f",$amount_grades_total);    //班级收费
        $item_end['amount_goods'] = sprintf("%.2f",$amount_goods_total);    //物品收费
        $item_end['amount_course_balance'] = sprintf("%.2f",$amount_course_total);    //课程收费余额
        $item_end['amount_grades_balance'] = sprintf("%.2f",$amount_grades_total);    //班级收费余额
        $item_end['amount_goods_balance'] = sprintf("%.2f",$amount_goods_total);    //物品收费余额
        $item_end['stay_amount'] = sprintf("%.2f",$stay_amount);  //待收款
        $item_end['balance'] = sprintf("%.2f",$balance);  //学费余额
        $item_end['stay_distributed'] = sprintf("%.2f",$stay_distributed);  //待分配
        $item_end['total_contract'] = $total_contract; //合同优惠前总额


        $listData['data'][count($listData['data'])] = $item_end;

        return $listData;
    }

    /*******单条订单记录*****/
    public function getContractinfo($param,$contract_number){

        $page = isset($param['page']) ? (int) $param['page'] : 1;
        $listRows = isset($param['limit']) ? (int) $param['limit'] : 10;
        $listData = self::where(['contract_number'=>$contract_number])
            ->paginate($listRows, false, ['page' => $page])
            ->toArray();
        $course_arr = '';
        $grades_course = '';
        $course_paid_nums = '';
        $grades_course_paid_nums = '';
        $course_elimination_nums = '';
        $grades_course_elimination_nums = '';



        $contract_id = '';
        $stay_distributed = 0;
        $CourseContractModel = new CourseContractModel();
        $GradesContractModel = new GradesContractModel();
        if (!empty($listData)) {
            foreach ($listData['data'] as &$item) {
                $contract_id = $item['id'];  //合同ID
                $course_arr = explode(',',$item['course']);
                $course_paid_nums = explode(',',$item['course_paid_nums']);;  //到款数量
                $grades_course = explode(',',$item['grades_course']);
                $grades_course_paid_nums =  explode(',',$item['grades_course_paid_nums']);;  //到款数量
                $course_elimination_nums = explode(',',$item['course_elimination']); //剩余课消
                $grades_course_elimination_nums = explode(',',$item['grades_course_elimination']); //剩余课消
                $stay_distributed = $item['stay_distributed'];
            }
        }

        $res_course = $CourseContractModel->where(['contract_id' => $contract_id])->select();
        $res_grades = $GradesContractModel->where(['contract_id' => $contract_id])->select();

        $listData['data'] = [];
        //课程
        foreach ($res_course as $value){
            $item_course = [];
            $item_course['project_id'] = $value['id'];
            $item_course['project_name'] = CourseModel::get(['id' => $value['course_id']])['course_name'];
            $item_course['project_nums']  = $value['class_num'];  //签约数量
            $item_course['project_type']  = 1;  //类型1：课程
            //算单价
            $item_course['project_price'] = round(((($value['net_receipts'] - $value['assessed_amount'])/($value['class_num']))/100),2); //(折后应收 - 分摊金额)/nums
            $item_course['project_total_amount'] = ($value['net_receipts'] - $value['assessed_amount']) / 100; //应收金额

            $key = array_search($value['course_id'], $course_arr);
            $item_course['project_paid_nums'] = $course_paid_nums[$key];  //到款数量
            $item_course['project_paid_amount'] = $value['payment'] / 100; //到款金额

            $item_course['project_surplus_nums'] = $course_elimination_nums[$key];  //剩余数量
            $item_course['project_surplus_amount'] = $value['payment_balance'] / 100; //剩余金额

            $item_course['project_stay_distributed'] = $stay_distributed;

            $listData['data'][] = $item_course;
        }

        //班级
        foreach ($res_grades as $value){
            $item_grades = [];
            $item_grades['project_id'] = $value['id'];
            $item_grades['project_name'] = GradesDetailsModel::get(['id' => $value['grades_id']])['grades_name'];
            $item_grades['project_nums']  = $value['class_num'];  //签约数量
            $item_grades['project_type']  = 2;  //类型1：班级
            //算单价
            $item_grades['project_price'] = round(((($value['net_receipts'] - $value['assessed_amount'])/($value['class_num']))/100),2); //(折后应收 - 分摊金额)/nums
            $item_grades['project_total_amount'] = ($value['net_receipts'] - $value['assessed_amount']) / 100; //应收金额

            $key = array_search($value['course_id'], $grades_course);
            $item_grades['project_paid_nums'] = $grades_course_paid_nums[$key];  //到款数量
            $item_grades['project_paid_amount'] = $value['payment'] / 100; //到款金额

            $item_grades['project_surplus_nums'] = $grades_course_elimination_nums[$key];  //剩余数量
            $item_grades['project_surplus_amount'] = $value['payment_balance'] / 100; //剩余金额

            $item_course['project_stay_distributed'] = $stay_distributed;

            $listData['data'][] = $item_grades;
        }


        return $listData;
    }

    //报读订单记录
    /**
     * 报读订单记录
     * modify by Small Y
     *
     * @param $param
     * @return array
     * @throws \think\exception\DbException
     */
    public function getOrderRecordList($param)
    {
        $page = isset($param['page']) ? (int) $param['page'] : 1;
        $listRows = isset($param['limit']) ? (int) $param['limit'] : 10;
        $where = [];
        $where['student_id'] = $param['id'];
        if(get_current_type() == 4 || get_current_type() == 5){
            $where['campus_id'] = get_current_campus_id();
        }elseif (get_current_type() == 2 || get_current_type() == 3){
            $where['campus_id'] = ['in',get_current_campus_id()];
        }
        $listData = self::where($where)
            ->paginate($listRows, false, ['page' => $page])
            ->toArray();
        if (!empty($listData)) {
            foreach ($listData['data'] as &$item) {

            }
        }
        return $listData;
    }
}